// pages/addNews/addNews.js
const httpUtil = require("../../utils/httpUtil.js");
const globalCache = require("../../utils/cache.js");
const util = require("../../utils/util.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    padding: "0px",
    newsType: 1,
    content: '',
    images: [],
    hidePlusButton: false,
    videoSrc: '',
    imageCount: 9,
    hideModal: true, //模态框的状态  true-隐藏  false-显示
    animationData: {},
    hideImageSelect: false,
    hideVideoSelect: false,
    uploadedUrls: [],
    mediaType: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var newsType = options.newsType;
    this.setData({
      newsType: newsType
    });

    this.setTitle();
    this.setPadding();
  },

  /**
   * 根据newsType类型设置不同的标题
   */
  setTitle: function () {
    var title = '发布动态'
    if (this.data.newsType == "2") {
      title = "发布作业"
    }
    wx.setNavigationBarTitle({
      title: title
    });
  },

  setPadding: function () {
    var that = this;
    //动态设置入口区域的高度
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          padding: ((res.windowWidth - 316) / 2) + "px"
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
 
  /**
   * 添加图片
   */
  addImage: function () {
    var that = this;
    that.setData({
      hideModal: false
    })
    var animation = wx.createAnimation({
      duration: 600,//动画的持续时间 默认400ms   数值越大，动画越慢   数值越小，动画越快
      timingFunction: 'ease',//动画的效果 默认值是linear
    })
    this.animation = animation
    setTimeout(function () {
      that.fadeIn();//调用显示动画
    }, 200)
  },

  /**
   * 点击遮罩层，隐藏底部弹出框
   */
  hideModal: function (e) {
    var that = this;
    var animation = wx.createAnimation({
      duration: 800,//动画的持续时间 默认400ms   数值越大，动画越慢   数值越小，动画越快
      timingFunction: 'ease',//动画的效果 默认值是linear
    })
    this.animation = animation
    that.fadeDown();//调用隐藏动画   
    setTimeout(function () {
      that.setData({
        hideModal: true
      })
    }, 720)//先执行下滑动画，再隐藏模块
  },

  //动画集
  fadeIn: function () {
    this.animation.translateY(0).step()
    this.setData({
      animationData: this.animation.export()//动画实例的export方法导出动画数据传递给组件的animation属性
    })
  },

  fadeDown: function () {
    this.animation.translateY(300).step()
    this.setData({
      animationData: this.animation.export(),
    })
  },
 
  /**
   * 选择图片
   */
  chooseImage: function () {
    var that = this;
    that.setData({
      hideModal: true
    })
    wx.chooseImage({
      count: that.data.imageCount,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: res => {
        var images = that.data.images.concat(res.tempFilePaths);
        var remainImageCount = that.data.imageCount - images.length;
        var hidePlusButton = false;
        if (remainImageCount <= 0) {
          hidePlusButton = true;
        }
        that.setData({
          hideVideoSelect: true,
          images: images,
          imageCount: remainImageCount,
          hidePlusButton: hidePlusButton,
        });
      }
    })
  },

  /**
   * 选择视频
   */
  chooseVideo: function () {
    var that = this;
    that.setData({
      hideModal: true
    })
    wx.chooseVideo({
      sourceType: ['camera'],
      maxDuration: 60,
      camera: 'back',
      success: res => {
        that.setData({
          videoSrc: res.tempFilePath,
          hidePlusButton: true,
          hideImageSelect: true
        })
      }
    })
  },

  /**
   * 
   */
  cancel: function () {
    this.setData({
      hideModal: true
    })
  },

  /**
   * 点击放大图片
   */
  enlargeImage: function (event) {
    var src = event.currentTarget.dataset.src;
    wx.previewImage({
      current: src, 
      urls: this.data.images
    })
  },
  
  /**
   * 长按删除图片
   */
  deleteImage: function (event) {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确定要删除吗？',
      success: function (sm) {
        if (sm.confirm) {
          var index = event.currentTarget.dataset.index;
          var imageArray = that.data.images;
          imageArray.splice(index, 1);
          var hideVideoSelect = true;
          if (imageArray.length <= 0) {
            hideVideoSelect = false;
          }
          that.setData({
            images: imageArray,
            hidePlusButton: false,
            hideVideoSelect: hideVideoSelect,
          })
        } 
      }
    })
  },
  
  /**
   * 长按删除视频
   */
  deleteVideo: function () {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确定要删除吗？',
      success: function (sm) {
        if (sm.confirm) {
          that.setData({
            videoSrc: '',
            hideImageSelect: false,
            hidePlusButton: false,
          })
        }
      }
    })
  },

  /**
   * 获取内容
   */
  getContent: function (e) {
    this.setData({
      content: e.detail.value
    })
  },

  /**
   * 发布新闻/作业
   */
  submitData: function () {
    if (util.isEmpty(this.data.content) 
        && this.data.images.length <= 0 && util.isEmpty(this.data.videoSrc)) {
      return;
    }

    var data = new Object();
    data.path = [];
    var mediaType = 0;
    if (this.data.images.length > 0) {
      data.path = this.data.images;
      mediaType = 1;
    } else if(!util.isEmpty(this.data.videoSrc)) {
      data.path.push(this.data.videoSrc);
      mediaType = 2;
    }
    this.setData({
      mediaType: mediaType
    })
    var that = this;
    if (data.path.length > 0) {
      that.publishWithImage(data, that);
    } else {
      that.publish(that);
    }
  },

  publishWithImage: function (data, that) {
    wx.showLoading({
      title: "上传中...",
      mask: true
    })
    globalCache.retsetUploadFileUrl();
    httpUtil.uploadFile("uploadFile", data, function (res, that) {
      wx.hideLoading();
      that.publish(that);
    }, that);
  },

  publish: function(that) {
    var data = new Object();
    data.content = that.data.content;
    data.imageUrlList = globalCache.getUploadFileUrl();
    if (data.imageUrlList == "") {
      data.imageUrlList = null;
    }
    data.newsType = that.data.newsType;
    data.mediaType = that.data.mediaType;
    data.teamId = globalCache.getCurrentTeamId();
    data.userId = globalCache.getUserId();
    httpUtil.requestPost("publishNews", data, function (res, that) {
      globalCache.removeFileUrl();
      wx.navigateBack({
        delta: 1
      });
    }, that, "提交中...");
  }
})